package com.im.service.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.im.service.common.Result;
import com.im.service.domain.entity.ImGroup;
import com.im.service.domain.entity.ImGroupUser;
import com.im.service.service.ImGroupService;
import com.im.service.service.ImGroupUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * im-群用户 前端控制器
 * </p>
 *
 * @author 刘志强
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/imGroupUser")
@CrossOrigin
@Slf4j
@Api(tags = "IM群组用户相关接口")
public class ImGroupUserController {

    @Autowired
    private ImGroupUserService groupUserService;
    @Autowired
    private ImGroupService groupService;

    @PostMapping("/batchAddGroupUser/{groupId}")
    @ApiOperation(value = "批量添加群用户")
    public Result batchAddGroupUser(@PathVariable("groupId") Long groupId, @RequestBody List<Long> userIds) {
        return groupUserService.batchAddGroupUser(groupId, userIds);
    }


    @GetMapping("/myGroup")
    @ApiOperation(value = "我的群组")
    public Result<List<ImGroup>> myGroup() {
        return groupUserService.myGroup(StpUtil.getLoginIdAsLong());
    }


    @DeleteMapping("/removeGroupUser")
    @ApiOperation(value = "移除群用户")
    public Result removeGroupUser(Long id) {
        ImGroupUser imGroupUser = groupUserService.getById(id);
        ImGroup imGroup = groupService.getById(imGroupUser.getGroupId());
        groupUserService.removeGroupUser(imGroup, imGroupUser.getId(), 2);
        return Result.ok();
    }

    @DeleteMapping("/exitGroup")
    @ApiOperation(value = "退群")
    public Result exitGroup(Long groupId) {
        ImGroupUser imGroupUser = groupUserService.getOne(
                Wrappers.lambdaQuery(ImGroupUser.class)
                        .eq(ImGroupUser::getGroupId, groupId)
                        .eq(ImGroupUser::getUserId, StpUtil.getLoginIdAsLong())
                        .last("limit 1")
        );
        if (ObjUtil.isNotNull(imGroupUser)) {
            ImGroup imGroup = groupService.getById(imGroupUser.getGroupId());
            groupUserService.removeGroupUser(imGroup, imGroupUser.getId(), 2);
        }
        return Result.ok();
    }
}
